package com.springapp.mvc.controllers;

import com.springapp.mvc.services.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class PersonController {

    @Autowired
    private PersonService personService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String init(ModelMap model) {


        model.addAttribute("message", "Hello world!");
        return "hello";
    }

    @RequestMapping(value = "/personTable", method = RequestMethod.GET)
    public String showPersons(@RequestParam(required = false) Boolean success,
                              ModelMap modelMap) {
        if(success != null) {
            modelMap.addAttribute("success", success);
        }
        modelMap.addAttribute("persons", personService.findAll());

        return "personTable";
    }

    @RequestMapping(value = "/deletePerson/{personId}", method = RequestMethod.GET)
    public String deletePerson(@PathVariable("personId") int id) {
        personService.deleteById(id);
        return "redirect:/personTable";
    }

    @RequestMapping(value = "/addPerson", method = RequestMethod.GET)
    public String addPerson() {

        return "addPerson";
    }

    @RequestMapping(value = "/addPersonAction", method = RequestMethod.POST)
    public String addPersonAction(@RequestParam String name,
                                  @RequestParam String age) {

        boolean successValue = personService.add(name, age);

        return "redirect:/personTable?success=" + successValue;

    }
}